import datetime
from typing import List, Optional, Sequence
from pydantic import BaseModel, Field, validator
from schemas import _validator


class Rule(BaseModel):
    max_draw_times: int
    person_day_draw_times: int
    point: int
    person_max_win_times: int
    day_max_win_times: int
    draw_mode: int
    total_win_rate: str
    goods_provide_interval: int


class LotteryBase(BaseModel):
    accesstoken: Optional[str]
    name: str
    type: int
    start_time: str
    end_time: str

    rules: Rule


class LotteryCreate(LotteryBase):

    create_time: str = datetime.datetime.now().strftime("%Y-%m-%d %X")
    # 转json
    container_json_encode = validator(
        "rules", allow_reuse=True)(_validator.container_json_encode)


class LotteryAdjust(LotteryCreate):
    id: int

    class Config:
        schema_extra = {
            "example": {
                  "accesstoken": "TOKEN3590",
                  "id": 1,
                  "name": "123123",
                  "type": 1,
                  "start_time": "2020-10-01 00:00:00",
                  "end_time": "2023-10-01 00:00:00",
                  "template_id": 1296,
                  "rules": {
                    "max_draw_times": 2,
                    "person_day_draw_times": 3,
                    "point": 20,
                    "person_max_win_times": 5,
                    "day_max_win_times": 5,
                    "draw_mode": 1,
                    "total_win_rate": "20%",
                    "goods_provide_interval": 0
                  }
                }
        }


class LotteryDelete(BaseModel):
    id: List[int]


class Lottery(LotteryBase):
    id: int
    create_time: str

    # 转 dict
    container_json_decode = validator("rules", pre=True, allow_reuse=True)(_validator.container_json_decode)
    # datetime 转换
    datetime_str_decode = validator(
        "start_time", "end_time", "create_time", pre=True, allow_reuse=True)(
        _validator.datetime_str_decode)

    class Config:
        orm_mode = True


if __name__ == '__main__':
    from sql_app.database import SessionLocal
    from sql_app.models import TActivityLottery

    db = SessionLocal()
    res = db.query(TActivityLottery).filter(TActivityLottery.id==1).scalar()
    res.name = "MERGE测试测试"
    db.merge(res)
    db.refresh(res)
    db.commit()
